package com.example.sendmessage;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {
    EditText edReceive;
    EditText edPost;
    EditText edInputIP;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnUDP = findViewById(R.id.btn_udp);
        edReceive = findViewById(R.id.edReceive);
        edPost = findViewById(R.id.edPost);
        edInputIP = findViewById(R.id.edInputIP);
        setImmersiveWindows();

        btnUDP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        UDP udp = UDP.getInstance();
                        String msg = edPost.getText().toString();
                        String ip = edInputIP.getText().toString();
                        udp.send(msg,ip);
//                        EventBus.getDefault().post(msg);
                    }
                }).start();
//                edPost.setText("");
            }
        });

        EventBus.getDefault().register(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleUDPData(UDPMessage msg){
        String temp = edReceive.getText().toString();
        edReceive.setText(temp+"\n"+msg.getMsg());
    }

    /**
     * 获取系统状态栏的高度
     * @return
     */
    protected int  getStateBarHeight(){
        int result = 0;
        int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = this.getResources().getDimensionPixelSize(resourceId);
        };
        return result;
    }

    /**
     * 设置沉浸式窗口
     */
    protected  void setImmersiveWindows(){
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            View root = ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
            root.setPadding(0,getStateBarHeight(),0,0);
        }
    }
}